package cn.hinglo.gameclaw.admin.service;

import cn.hinglo.gameclaw.admin.dao.NoticeDao;
import cn.hinglo.gameclaw.data.utils.FieldUtils;
import cn.hinglo.gameclaw.data.utils.FileImageUtils;
import cn.hinglo.gameclaw.data.utils.IdUtils;
import cn.hinglo.gameclaw.user.bean.Notice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;


/**
 * @createTime: 2018/1/8
 * @author: HingLo
 * @description: 公告管理实体类
 */
@Service
public class NoticeService {
    private final NoticeDao noticeDao;

    @Autowired
    public NoticeService(NoticeDao noticeDao) {
        this.noticeDao = noticeDao;
    }

    /**
     * 返回全部的通知/公告类型
     *
     * @return 返回查询结果集合
     */
    public List<Notice> findAllNoticeService() {
        List<Notice> list = noticeDao.selectAll();
        return list;
    }

    /**
     * 添加公告信息
     *
     * @param notice 公告信息实体类
     * @return 返回添加结果
     */
    public boolean addService(Notice notice, MultipartFile img) {
        int type = notice.getType();
        if (type == 1 || type == 2) {
            notice.setId(IdUtils.getId());
            notice.setDate(new Date());
            //检测该img是否是图片类型并生成一个图片名称
            String fileName = FileImageUtils.createFileNameUtils(img);
            notice.setIcon(fileName);
            notice.setStatus(false);
            // 保存图片并添加数据到数据库中
            return FileImageUtils.saveImageUtils(img, fileName, FieldUtils.IMAGE_7) && noticeDao.insert(notice) > 0;
        }
        return false;
    }

    public List<Notice> findTypeService() {
        Notice notice = new Notice().setStatus(true).setType(1);
        List<Notice> list = noticeDao.select(notice);
        list.forEach(x -> x.setIcon(FieldUtils.URL + "/user/i/img?type=" + FieldUtils.IMAGE_7 + "&subject=" + x.getIcon()));
        return list;
    }

    /**
     * 修改通知的状态信息，启用或者禁用
     *
     * @param id     通知的Id
     * @param status 状态
     * @return 是否修改成功
     */
    public boolean statusService(String id, Boolean status) {
        Notice notice = new Notice().setStatus(status).setId(id);
        return noticeDao.updateByPrimaryKeySelective(notice) == 1;
    }
}
